package com.uetoken.cn.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.ConfigBean;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.utils.AppUpdate;
import com.uetoken.cn.utils.ArithUtils;
import com.uetoken.cn.utils.CacheUtil;
import com.uetoken.cn.view.DialogHelper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author 谢杨
 * @date 2018年7月23日16:17:48
 * 关于我们
 */
public class AboutUsActivity extends BaseActivity {

    @BindView(R.id.rl_about_us_features)
    RelativeLayout mRlFeatures;
    @BindView(R.id.rl_about_us_version_update)
    RelativeLayout mRlVersionUpdate;
    @BindView(R.id.rl_about_us_language)
    RelativeLayout mRlLanguage;
    @BindView(R.id.tv_about_us_language_current_language)
    TextView mTvCurrentLanguage;
    @BindView(R.id.iv_about_us_back)
    ImageView mIvBack;
    @BindView(R.id.tv_about_us_title)
    TextView mTvTitle;
    @BindView(R.id.tv_about_us_change_mode_up)
    TextView mTvChangeModeUp;
    @BindView(R.id.tv_about_us_change_mode_down)
    TextView mTvChangeModeDown;
    @BindView(R.id.tv_about_us_version)
    TextView mTvVersion;
    @BindView(R.id.tv_clear_cache_current_size)
    TextView mTvCurrentCacheSize;

    /**
     * 定义一个变量来进行计数
     */
    private int i = 0;

    private boolean testModeFlag = true;
    private String mTotalCacheSize = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_about_us;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);

        mIvBack.setVisibility(View.VISIBLE);
        mTvTitle.setText(getString(R.string.tv_about));
        mTvCurrentLanguage.setText(R.string.str_base_language);
        mTvVersion.setText(AppUtils.getAppVersionName());

        try {
            mTotalCacheSize = CacheUtil.getTotalCacheSize(AboutUsActivity.this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ArithUtils.compare(mTotalCacheSize, "0") > 0) {
            mTvCurrentCacheSize.setText(mTotalCacheSize + "M");
        } else {
            mTvCurrentCacheSize.setText("");
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public void init() {

    }

    @OnClick({R.id.rl_about_us_features, R.id.rl_about_us_version_update, R.id.rl_about_us_language,
            R.id.tv_about_us_change_mode_up, R.id.tv_about_us_change_mode_down, R.id.iv_about_us_back, R.id.rl_clear_cache})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_about_us_back:
                finish();
                break;
            case R.id.rl_about_us_features:
                toWebActivity();
                break;
            case R.id.rl_about_us_version_update:
                checkAppUpdate();
                break;
            case R.id.rl_about_us_language:
                startActivity(new Intent(this, LanguageSelectActivity.class));
                break;
            case R.id.tv_about_us_change_mode_up:
                if (testModeFlag) {
                    i++;
                    testModeFlag = false;
                }
                if (i == 3) {

                    String mode;
                    if (Constant.isTestMode) {
                        //如果为测试模式,保存值为false，下次启动app就是正式模式
                        mode = getResources().getString(R.string.str_current_mode_is_test_will_switch_formal);
                        showChangeModeDialog(mode, false);
                    } else {
                        //如果为正式模式,保存值为true，下次启动app就是测试模式
                        mode = getResources().getString(R.string.str_current_mode_is_formal_will_switch_test);
                        showChangeModeDialog(mode, true);
                    }

                }
                break;
            case R.id.tv_about_us_change_mode_down:
                if (!testModeFlag) {
                    i++;
                    testModeFlag = true;
                }
                break;
            case R.id.rl_clear_cache:
                doClearCacheShow();
                break;


        }
    }

    private void doClearCacheShow() {
        DialogHelper.showMessageDialog(AboutUsActivity.this, null,
                getString(R.string.str_clear_cache_tip), getString(R.string.str_cancel), getString(R.string.str_confirm), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        //取消
                        dialog.dismiss();
                    }
                }, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        //确定
                        dialog.dismiss();
                        try {
                            CacheUtil.cleanAllData(AboutUsActivity.this);
                            mTotalCacheSize = CacheUtil.getTotalCacheSize(AboutUsActivity.this);
                            ToastUtils.showShort(getString(R.string.str_clear_cache_complete));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (ArithUtils.compare(mTotalCacheSize, "0") > 0) {
                            mTvCurrentCacheSize.setText(mTotalCacheSize + "M");
                        } else {
                            mTvCurrentCacheSize.setText("");
                        }
                    }
                });
    }

    /**
     * @param mode       当前模式
     * @param isTestMode 是否测试模式
     */
    private void showChangeModeDialog(String mode, final boolean isTestMode) {
        new QMUIDialog.MessageDialogBuilder(this).setTitle(getResources().getString(R.string.str_mode_switch)).setMessage(mode)
                .addAction(getResources().getString(R.string.str_cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        //初始化标识的值
                        i = 0;
                        testModeFlag = true;
                    }
                }).addAction(getResources().getString(R.string.str_confirm), new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(final QMUIDialog dialog, int index) {
                dialog.dismiss();
                //清空保存在本地的所有配置信息
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).clear();

                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).clear();

                //将是否是测试或者正式模式的boolean值保存下来
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.SP_MODE_CHANGE, isTestMode);

                final QMUITipDialog qmuiTipDialog = new QMUITipDialog.Builder(AboutUsActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                        .setTipWord("正在切换")
                        .create();
                qmuiTipDialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        qmuiTipDialog.dismiss();
                        AppUtils.relaunchApp();
                    }
                }, 3000);
            }
        }).setCancelable(false).setCanceledOnTouchOutside(false).show();
    }

    /**
     * 跳转webactivity
     */
    private void toWebActivity() {
        String config = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.SP_CONFIG_INFO, "");

        if (!TextUtils.isEmpty(config)) {
            Gson gson = new Gson();
            ConfigBean.DataBean dataBean = gson.fromJson(config, ConfigBean.DataBean.class);
            String synopsis = new String(EncodeUtils.base64Decode(dataBean.getSynopsis()));
            Intent intent = new Intent(this, WebActivity.class);
            intent.putExtra(Constant.TO_WEBVIEW_URL, synopsis);
            startActivity(intent);
        }
    }

    /**
     * 检查app更新
     */
    private void checkAppUpdate() {
        String dataBeanStr = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.SP_CONFIG_INFO, "");
        try {
            ConfigBean.DataBean dataBean = new Gson().fromJson(dataBeanStr, ConfigBean.DataBean.class);
            //服务器返回的android版本
            String androidversion = new String(EncodeUtils.base64Decode(dataBean.getAndroidversion()));
            //升级地址
            String updateUrl = new String(EncodeUtils.base64Decode(dataBean.getAndroidurl()));
            //升级描述
            String androidcontent = new String(EncodeUtils.base64Decode(dataBean.getAndroidcontent()));
            //获取本地的versionName
            String versionName = AppUtils.getAppVersionName();
            String regEx = "[^0-9]";
            Pattern p = Pattern.compile(regEx);
            Matcher m1 = p.matcher(androidversion);
            Matcher m2 = p.matcher(versionName);
            //网络返回的版本号转为可以比较的整数
            int netVersion = Integer.parseInt(m1.replaceAll("").trim());
            //本地的版本号
            int localVersion = Integer.parseInt(m2.replaceAll("").trim());
            //有升级版本
            if (netVersion > localVersion) {
                AppUpdate appUpdate = new AppUpdate(AboutUsActivity.this);
                appUpdate.showUpdateDialog(updateUrl, androidversion, androidcontent, false);
            } else {
                ToastUtils.showShort(getResources().getString(R.string.str_currently_the_latest_version));
            }
        } catch (JsonParseException e) {
            ToastUtils.showShort(getResources().getString(R.string.str_json_parse_exception));
        }
    }

}
